package cn.lkp.mall.authserver.controller;

import cn.lkp.common.constant.AuthServerConstant;
import cn.lkp.common.utils.HttpUtils;
import cn.lkp.common.utils.R;
import cn.lkp.mall.authserver.feign.MemberFeignService;
import cn.lkp.common.vo.MemberVo;
import cn.lkp.mall.authserver.vo.SocialUser;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Controller
public class OAuthController {
    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 社交登陆回调
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String login(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String,String> map = new HashMap<>();
        map.put("client_id","3809061918");
        map.put("client_secret","de9797a7191add1fbc6666c9c252a2d4");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.mall.com/oauth2.0/weibo/success");
        map.put("code",code);
        //根据code换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token",
                "post", new HashMap<>(), map, new HashMap<>());
        if(response.getStatusLine().getStatusCode()==200){
            //获取到access_token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道当前是哪个社交用户登陆了，如果是第一次登陆，会将社交账号存到数据库的会员表中
            //远程调用会员服务oauthLogin，进行登陆或注册
            R r = memberFeignService.oauthLogin(socialUser);
            if(r.getCode()==0){
                MemberVo loginUser = r.getData(new TypeReference<MemberVo>(){});
                session.setAttribute(AuthServerConstant.LOGIN_USER,loginUser);
                log.info("登陆成功，用户信息：",loginUser.toString());
                return "redirect:http://mall.com";
            }else {
                return "redirect:http://auth.mall.com/login.html";
            }
        }else {
            return "redirect:http://auth.mall.com/login.html";
        }
    }
}
